iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 3
0
自我挑戰組

各種筆記系列 第 3

[Kata] Clojure - Day 3

  • 分享至 

  • xImage
  •  

Recursion 101

You will be given two positive integers a and b and your task will be to apply the following operations:
比較兩個整數,並依據下列規則回傳 list [a b]

i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii);
ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii);
iii) If b ≥ 2*a, set b = b - 2*a, and repeat step (i). Otherwise, return [a,b].

Given test:

(ns codewars.core-test
  (:require [clojure.test  :refer :all]
            [kata.core :refer :all]))

(deftest example-tests
         (is (= (solve 6 19) '(6 7)))
         (is (= (solve 2 1) '(0 1)))
         (is (= (solve 22 5) '(0 1)))
         (is (= (solve 2 10) '(2 2)))
         (is (= (solve 8796203 7556) '(1019 1442)))
         (is (= (solve 19394 19394) '(19394 19394))))

Solution

(ns kata.core)

(defn solve
  [a b]
  (cond (or (zero? a) (zero? b)) (list a b)
        (>= a (* 2 b)) (recur (- a (* 2 b)) b)
        (>= b (* 2 a)) (recur a (- b (* 2 a)))
        :else (list a b)))

上一篇
[Kata] Clojure - Day 2
下一篇
[Kata] Clojure - Day 4
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言